package com.zj.sy.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public  class BeanUtil {

	
	/**
	* @Title: copy
	* @Description: 类属性复制
	* @param @param source
	* @param @param target    参数
	* @return void    返回类型
	* @throws
	* @author Orange
	* @date 2019年4月3日
	*/
	public static void copy(Object source, Object target){
		org.springframework.beans.BeanUtils.copyProperties(source, target);
	}

	/**
	 * 只能复制editable的属性
	 * @param source
	 * @param target
	 * @param editable
	 */
	public static void copyWithEditable(Object source, Object target, Class<?> editable){
		org.springframework.beans.BeanUtils.copyProperties(source, target, editable);
	}

//	/**
//	 * 不复制ignoreClass的属性
//	 * @param source
//	 * @param target
//	 * @param ignoreClass
//	 */
//	public static void copyWithIgnore(Object source, Object target, Class<?> ignoreClass){
//		var fields = ignoreClass.getDeclaredFields();
//		var ingores = new String[fields.length];
//		for (int i = 0; i < fields.length; i++) {
//			ingores[i] = fields[i].getName();
//		}
//		BeanUtils.copyProperties(source, target, ingores);
//	}

	public static String getValueByFieldName(String fieldName, Object source) {
		JSONObject obj = JSON.parseObject(JSONUtil.toJSONString(source));
		return obj.getString(fieldName);
	}

	/**
	 * @name: 克隆source为新对象
	 * @author Peach
	 * @date:2018/9/4
	 */
	public static <T> T cloneNewObject(Object source, Class<T> clazz){
		T t = null;
		try {
			t = clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		BeanUtil.copy(source,t);
		return t;
	}


	/**
	 * @Title: newTclass
	 * @Description: 实例化泛型类
	 * @param @param
	 *            clazz
	 * @param @return
	 * @param @throws
	 *            InstantiationException
	 * @param @throws
	 *            IllegalAccessException 参数
	 * @return T 返回类型
	 * @throws @author
	 *             Orange
	 * @date 2018年1月16日
	 */
	public static <T> T newTclass(Class<T> clazz) {
		T a = null;
		try {
			a = clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return a;
	}

	public static Object[] getEntities(Object target, Class<?>[] objs) {
		Object[] entities = new Object[objs.length];
		int count = 0;
		for (Class<?> o : objs) {
			Object entity = null;
			try {
				entity = o.newInstance();
			} catch (Exception e) {
				continue;
			}
			if (target != null)
				copy(target, entity);
			entities[count ++] = entity;
		}
		return entities;
	}
}
